package com.shelpe.services.sinbad.service.rpt;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.shelpe.services.sinbad.controller.dto.EffectDto;
import com.shelpe.services.sinbad.entity.jpa.Campaign;
import com.shelpe.services.sinbad.model.RptKeyword;
import com.shelpe.services.sinbad.model.RptKeywordParam;
import com.shelpe.services.sinbad.repository.jpa.CampaignRepository;
import com.shelpe.services.sinbad.service.RptKeywordService;

@Service
public class CampaignService {
	@Autowired
	private CampaignRepository campaignRepository;
	@Autowired
	private RptKeywordService rptKeywordService;

	public EffectDto campaignMetric(long campaignID, String startDate, String endDate, String device) {
		Campaign campaign = this.campaignRepository.findOne(campaignID);
		Assert.notNull(campaign, "该计划不存在");
		List<Integer> sources = new ArrayList<Integer>();
		if ("all".equals(device)) {
			sources.add(1);
			sources.add(2);
			sources.add(4);
			sources.add(5);
		} else if ("mobile".equals(device)) {
			sources.add(4);
			sources.add(5);
		} else if ("pc".equals(device)) {
			sources.add(1);
			sources.add(2);
		} else if ("instation".equals(device)) {
			sources.add(1);
			sources.add(4);
		} else if ("outstation".equals(device)) {
			sources.add(2);
			sources.add(5);
		} else if ("pcin".equals(device)) {
			sources.add(1);
		} else if ("pcout".equals(device)) {
			sources.add(2);
		} else if ("mobilein".equals(device)) {
			sources.add(4);
		} else if ("mobileout".equals(device)) {
			sources.add(5);
		}
		RptKeyword rpt = rptKeywordService.getCampaignSummariesMetricNew(campaign.getUserID(), campaignID, startDate,
				endDate, "(" + StringUtils.join(sources, ",") + ")");
		EffectDto dto = new EffectDto();
		if (rpt != null) {
			dto.from(rpt);
		}
		return dto;
	}

	public List<EffectDto> campaignTrend(long campaignID, String startDate, String endDate, String device) {
		Campaign campaign = this.campaignRepository.findOne(campaignID);
		Assert.notNull(campaign, "该计划不存在");
		RptKeywordParam param = RptKeywordParam.init();
		param.setUserId(campaign.getUserID());
		param.setCampaignId(campaignID);
		if (device != null) {
			param.setupDevice(device);
		}
		param.setupDate(startDate, endDate);

		List<RptKeyword> rpts = rptKeywordService.getReportsTrendByDate(param);
		List<EffectDto> dtos = new ArrayList<EffectDto>();
		if (rpts != null) {
			for (RptKeyword rpt : rpts) {
				EffectDto dto = new EffectDto();
				dto.from(rpt);
				dtos.add(dto);
			}
		}
		return dtos;
	}
}
